package com.zjitc.backend_shop.controller.Admin;


import com.zjitc.backend_shop.pojo.Category;
import com.zjitc.backend_shop.service.CategoryService;
import com.zjitc.backend_shop.utils.APIResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;


@Controller
@RestController
@RequestMapping("/admin/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public APIResponse<List<Category>> findAll(HttpServletRequest request) {
        List<Category> categories = categoryService.findAllCategory();
        for (Category category : categories) {
            if (category.getPid() != 0) {
                category.setPicture(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + category.getPicture());
            }
        }
        APIResponse<List<Category>> apiResponse = new APIResponse<>(0, "", categories);
        return apiResponse;
    }

    @GetMapping
    public APIResponse<Category> findById(@RequestParam(value = "id", required = false) Integer id) {
        Category category = categoryService.findCategoryById(id);
        APIResponse<Category> apiResponse = new APIResponse<>(0, "", category);
        return apiResponse;
    }

    @PostMapping("/add")
    public APIResponse addCategory(@RequestBody Category category) {
        // 调用服务层方法保存分类
        if (category.getPid() == null) {
            category.setPid(0);
        }
        int id = categoryService.addCategory(category);
        // 返回成功的 API 响应
        return new APIResponse(0, "新增成功", new HashMap<String, Integer>() {{
            put("insertId", id);
        }});
    }

    //修改分类
    @PostMapping("/save")
    public APIResponse saveCategory(@RequestBody Category category) {
        int flag = categoryService.updateCategory(category);
        // 检查修改是否成功
        if (flag <= 0) {
            return new APIResponse(1000, "修改失败，分类不存在", null);
        }
        return new APIResponse(0, "修改成功", null);
    }

    @PostMapping("/del")
    public APIResponse deleteCategory(@RequestBody Category category) {
        if ( category.getId() == null) {
            return new APIResponse(1000, "删除失败，分类不存在", null);
        }
        int flag = categoryService.deleteCategory(category.getId());
        // 检查删除是否成功
        if (flag <= 0) {
            return new APIResponse(1000, "删除失败，分类不存在", null);
        }
        return new APIResponse(0, "删除成功", null);
    }

}
